package study.springboot.validation.support.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import study.springboot.validation.support.result.Result;
import study.springboot.validation.support.result.Results;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理通用异常
     *
     * @param ex -Exception
     * @return Result
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception ex) {
        log.error("", ex);
        return Results.ok();
    }

    /**
     * 处理参数异常
     *
     * @param ex -MethodArgumentNotValidException
     * @return Result
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        //
        BindingResult result = ex.getBindingResult();
        //
        FieldError error = result.getFieldError();
        //
        String code = error.getCode();
        String field = error.getField();
        String message = error.getDefaultMessage();

        log.info(">>>>>> {} {} {}", field, code, message);
        return Results.ok();
    }
}
